/************************************************************************/
// Copyright (C) 2016, han_gangbiao. All rights reserved.
// Use of this source code is governed by a GPL-v2 license that can be found in the License file.
// 
// [Time]:      2016-1-4 21:53:17
// [Author]:    han_gangbiao [http://my.oschina.net/jackhen]
// [Info]:      
/************************************************************************/

#include "xthread.h"

BEG_NS_SMART

void* threadbase_t::threadFunc(void* arg)
{
	threadbase_t* thr = (threadbase_t*)arg;
	if( thr ==0 )
	{
		return 0;
	}
	while(thr->isRunning())
	{
		if(thr->run() < 0) {
			printf("thread will exiting because of run() < 0.\n");
			break;
		}
	}
	{//stopped
		thr->m_running = false;
	}
	printf("thread stop.\n");
	return 0;
}

threadbase_t::threadbase_t()
{
	m_tid = 0;
	m_running = false;
}
threadbase_t::~threadbase_t() { stop(); }

int threadbase_t::start()
{
	if(m_running)
	{
		return 0;
	}
	m_running = true;
	int ret = pthread_create(&m_tid, NULL, threadFunc, this);
	if(ret != 0)
	{
		m_running = false;
		return -1;
	}
	return 0;
}

int threadbase_t::stop()
{
	if(isRunning())
	{
		m_running = false;
		void* tmp = NULL;
		pthread_join(m_tid, &tmp);
	}
	return 0;
}



END_NS_SMART

